package rov.ui.view;


import rov.ui.WindowManager;
import rov.ui.widget.PodPanel;
import rov.ui.widget.Graph;
import rov.data.LogManager;
import rov.data.PreferencesManager;
import rov.data.SensorData;
import rov.util.Utils;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

import java.util.ArrayList;
import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.NoRouteToHostException;


// displays sensor (temperature, current, voltage, etc.) data
public class SensorsView implements IView
{
    private static final String TITLE = "Sensors";

    private LogManager mLogger;
    private PreferencesManager mPrefs;
    private ArrayList<SensorData> mSensors;
    private Container mWindow;
    private JPanel mRoot;


    public String getTitle()
    {
        return TITLE;
    }

    public void create()
    {
        mLogger = LogManager.getShared();
        mPrefs = PreferencesManager.getDefaultSimple(false);

        if (mPrefs == null)
        {
            JOptionPane.showMessageDialog(null, "Could not get preferences manager", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String hints = Utils.run("arp -a");
        String myConfig = Utils.run("ifconfig");
        String guessPattern = myConfig.replaceAll("\n", " ").replaceAll(".*:((?:(?!255)\\d{1,3})\\.\\d{1,3}\\.\\d{1,3}\\.)\\d{1,3}.*", "$1");
        String guessIp = "";

        if (guessPattern.length() <= 15) {
System.out.println("searching ip");
            guessIp = hints.replaceAll("\n", " ").replaceAll(".*\\(" + guessPattern + "((?:(?!1\\s)(?!255))\\d{1,3}).*", guessPattern + "$1");
        }

	if (guessIp.length() > 15){
System.out.println("no match");
            guessIp = hints.replaceAll("\n", " ").replaceAll(".*\\(((?:(?!255)\\d{1,3})\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*", "$1");

	    if (guessIp.length() > 15){System.out.println("no match again: " + guessIp);
                guessIp = "";}
        }

System.out.println("conf: " + myConfig);
System.out.println("arp: " + hints);
System.out.println("pat: \"" + guessPattern + "\"");
System.out.println("guess: \"" + guessIp + "\"");

        Object addr = JOptionPane.showInputDialog(null, "Enter ROV IP Address. Hints:\n" + hints + "\n", "Network Connection", JOptionPane.QUESTION_MESSAGE, null, null, guessIp);

if (addr == null)
  return;

        mSensors = new ArrayList<SensorData>();

        String[] sensorNames = new String[] { "Motor Controller Pod", "Processor Pod" };
        String[] voltageNames = new String[] { "Motor Controller Voltage", "BeagleBoard Voltage" };
        String[] placements = new String[] { BorderLayout.WEST, BorderLayout.EAST };
        int[] tempIndexes = new int[] { 1, 2 };
        int[] minVals = new int[] { 6, 1 };
        int[] maxVals = new int[] { 13, 6 };
        double[] lines = new double[] { 10.8, 4.3 };
        JPanel podsLabel = new JPanel(new BorderLayout());
        JPanel pods = new JPanel(new BorderLayout());
        mRoot = new JPanel();

        JLabel label = new JLabel("Temperatures", JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(Color.white);
        //label.setBackground(Color.black);
        //label.setForeground(Color.white);
        podsLabel.add(label, BorderLayout.NORTH);
        podsLabel.add(pods, BorderLayout.CENTER);
        pods.setBorder(BorderFactory.createLineBorder(Color.black));
        //pods.setBorder(BorderFactory.createLineBorder(Color.white));
        //mRoot.setBackground(Color.black);
        mRoot.add(podsLabel);

        label = new JLabel("Bow", JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(Color.white);
        //label.setBackground(Color.black);
        //label.setForeground(Color.white);
        pods.add(label, BorderLayout.NORTH);

        label = new JLabel("Stern", JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(Color.white);
        //label.setBackground(Color.black);
        //label.setForeground(Color.white);
        pods.add(label, BorderLayout.SOUTH);

        for (int i = 0; i < sensorNames.length; i++)
        {
            try
            {
                final SensorData sensor = new SensorData(addr.toString(), SensorData.START_PORT + i);

                mSensors.add(sensor);
                pods.add(new PodPanel(sensorNames[i], sensor, tempIndexes[i]), placements[i]);

                {
                    Graph g = new Graph(voltageNames[i], sensor, 0, new int[] { 30, 20, 10, 0 }, 700, minVals[i], maxVals[i]);
                    mRoot.add(g);
                    g.addLine(lines[i], Color.red);
                }

                if (i == 1)
                {
                    Graph g = new Graph("Pump Amperage", sensor, 1, new int[] { 30, 20, 10, 0 }, 700, 2400, 2700);
                    g.addLine(2590, Color.green);
                    g.addLine(2515, Color.red);
                    mRoot.add(g);
                }

                sensor.addListener(new ChangeListener()
                {
                    public void stateChanged(ChangeEvent e)
                    {
                        mWindow.repaint();

                        StringBuffer msg = new StringBuffer();

                        if (sensor.getNumVals() > 0)
                            msg.append(sensor.getValue(0));

                        for (int i = 1; i < sensor.getNumVals(); i++)
                            msg.append("\t" + sensor.getValue(i));

                        mLogger.log(LogManager.SENSOR_LOG, msg.toString());
                    }
                });
            }
            catch (IOException e)
            {
                if (!(e instanceof ConnectException || e instanceof UnknownHostException || e instanceof NoRouteToHostException))
                    e.printStackTrace();

                JOptionPane.showMessageDialog(null, "Could not connect to given address: \"" + addr.toString() + "\"\nDetails: \"" + e.getMessage() + "\"\nError type: " + e.getClass(), "Network Error", JOptionPane.ERROR_MESSAGE);
            }
        }

     	mWindow = WindowManager.getInstance().createWindow(TITLE, true, true, true, true, 310, 625);
        mWindow.add(mRoot);

for (int i = 0; i < mSensors.size(); i++)
  mSensors.get(i).start();

    }

    public void destroy()
    {
    }

    public void pause()
    {
    }

    public void resume()
    {
    }
}
